from flask import Flask, render_template, request, session, redirect, send_from_directory,make_response
from flask_cors import CORS
from flask_session import Session
from frameworks.utils.JsonResult import *
from frameworks.cores.LoadClass import *
from frameworks.cores.Config import *
from frameworks.utils.JsonResult2 import *
from controller.ApiController import *
from frameworks.utils.RedisUtil import *
import json
import os
import hashlib
import datetime
redis = RedisUtil()

server = Flask(__name__)

#from gevent import monkey

# 将python标准的io方法，都替换成gevent中的同名方法，遇到io阻塞gevent自动进行协程切换
#monkey.patch_all()

def create_app():
    app = Flask(__name__)
    CORS(app)
    return app


app = create_app()
app.config['JSON_AS_ASCII']=False
app.config['SESSION_TYPE'] = 'filesystem'

Session(app)

basepath = os.path.join(os.path.dirname(__file__))
config = Config(basepath)

apimap = config.getApi()
env = apimap["base"]
print(env)

print(basepath)

jsonResult = JsonResult2()

loader = LoadClass()

from views.common import common
from views.kaoshi import kaoshi

app.register_blueprint(common, url_prefix='/common')
app.register_blueprint(kaoshi, url_prefix='/kaoshi')

@app.route(env+"/",methods=['GET', 'POST'])
def index():
    css = "layui-this"
    indexcss = css
    fupancss = ""
    catcss = ""
    zhangtingcss = ""
    zhinengcss = ""
    if "username" in session:
        username = session['username']
    else:
        username = ""
    return render_template('/front/index.html',
                           username=username,
                           indexcss=indexcss,
                           catcss=catcss,
                           fupancss=fupancss,
                           zhangtingcss=zhangtingcss,
                           zhinengcss=zhinengcss,
                           )

@app.route(env+"/member",methods=['GET', 'POST'])
def member_index():
    if session.get("username") != None:
        return render_template(
            'index.html',
            username=session['username'],
            role=session['role']
        )
    else:
        return redirect("/",code=302,Response=None)

@app.route(env+"/login/api",methods=['POST'])
def loginapi():
    quert_json = request.get_data(as_text=True)
    userinfo = json.loads(quert_json)
    session['username'] = userinfo["username"]
    md = hashlib.md5()  # 获取一个md5加密算法对象
    md.update(userinfo["password"].encode('utf-8'))  # 制定需要加密的字符串
    rs = loader.load("controller.CommonController", "CommonController", {
        "func": "getAllData",
        "data": {"username": userinfo["username"], "password": md.hexdigest()},
        "model": "users",
        "fields": "*"
    })
    if len(rs) > 0:
        session["userid"] = rs[0]["id"]
        session["role"] = rs[0]["role"]
        return JsonResult.setOk("登录成功","{}")
    else:
        return JsonResult.setError("没有该用户，或者密码错误")

@app.route(env+"/reg/api",methods=['POST'])
def regapi():
    quert_json = request.get_data(as_text=True)
    userinfo = json.loads(quert_json)
    md = hashlib.md5()  # 获取一个md5加密算法对象
    md.update(userinfo["password"].encode('utf-8'))  # 制定需要加密的字符串
    loader.load("controller.CommonController", "CommonController", {
        "func": "add",
        "data": {"username":userinfo["username"],"password":md.hexdigest()},
        "model": "users"
    })
    session['username'] = userinfo["username"]
    return JsonResult.setOk("注册成功","{}")

@app.route(env+"/logout",methods=['GET'])
def logout():
    session["username"] = ""
    session.clear()
    return redirect('/',code=302,Response=None)

@app.route(env+"/login",methods=['GET', 'POST'])
def login():
    return render_template("front/login.html")

@app.route(env+"/reg",methods=['GET', 'POST'])
def reg():
    return render_template("front/reg.html")

@app.route(env+"/aacharts",methods=['GET'])
def aacharts():
    ck = request.args.get("ck","")
    al = redis.vget(ck)
    if al == None:
        return jsonResult.setOk([], "获取成功")
    else:
        print("=======read cache===============")
        return jsonResult.setOk(al, "获取成功")

@app.route(env+"/kaoshi",methods=['GET', 'POST'])
def kaoshi():
    sid = request.args.get("sid", "")
    paper_type = request.args.get("paper_type","")
    if paper_type == "自动组题":
        sid = "temp_223"
        erid = "temp_223"
        data = loader.load("controller.ExamPaperController", "ExamPaperController", {
            "func": "getRandomQuestion",
            "sid": sid
        })
    else:
        if sid == "":
            return "参数缺乏"
        erid = "erid_" + str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
        data = loader.load("controller.ExamPaperController", "ExamPaperController", {
            "func": "getExamPaper",
            "sid":sid
        })
        #将试卷答题信息存储在redis里，避免表格来回插入，如果提交试卷的话，再将此信息写入。
        redis.vset(erid+str(session["userid"]),datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    return render_template(
        "kaoshi.html",
        data=data,
        sid=sid,
        erid=erid,
        paper_type=paper_type,
        uid=session["userid"]
    )

@app.route(env+"/mustkaoshi",methods=['GET', 'POST'])
def mustkaoshi():
    sid = request.args.get("sid","")
    if sid == "":
        return "参数缺乏"
    erid = "erid_" + str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
    data = loader.load("controller.ExamPaperController", "ExamPaperController", {
        "func": "getExamPaper",
        "sid":sid
    })

    #将试卷答题信息存储在redis里，避免表格来回插入，如果提交试卷的话，再将此信息写入。
    ertid = loader.load("controller.ExamPaperController", "ExamPaperController", {
        "func": "addMustExamRecord",
        "sid": sid,
        "erid": erid,
        "userid": session["userid"]
    })

    return render_template(
        "mustkaoshi.html",
        data=data,
        sid=sid,
        erid=erid,
        ertid=ertid,
        uid=session["userid"]
    )

@app.route('/images/<dirmulu>/<image_name>')
def display_image(dirmulu,image_name):
    folder_name = 'c:/images/images/' + dirmulu + "/"
    print(folder_name)
    print(image_name)
    return send_from_directory(folder_name, image_name)

@app.route('/query_href')
def query_href():
    hreflist = {
        "data":[
        {"config": "百度", "data": "http://www.baidu.com"},
        {"config": "搜狐", "data": "http://www.sohu.com"}
    ]}
    return json.dumps(hreflist)

if __name__ == "__main__":
    app.run()
